/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hk.ces.oxfam.patch.OTWTeamCoordinator;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Map;
/**
 *
 * @author ivanlin
 */
public class ExportHandler
{
  private static final ExportHandler HANDLER = new ExportHandler();
  private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
  private Map<Integer, CompanyItem> allCompanyMap;

  public void doExport(List<ExportItem> items, Map<Integer, CompanyItem> allCompanyMap,
          List<CompanyItem> companyItems, List<DistrictItem> districtItems, List<RegionItem> regionItems, List<TougueItem> tougueItems) throws IOException
  {

    this.allCompanyMap = allCompanyMap;

    HSSFWorkbook workbook = new HSSFWorkbook(this.getClass().getResourceAsStream("/OTWTeamCoordinator.xls"));
    HSSFSheet sheet = workbook.getSheetAt(0);
    
    int rowNum = 1;
    for (ExportItem item : items)
    {
      HSSFRow row = sheet.createRow(rowNum++);
      String[] content = this.genContent(item);

      for (int i = 0; i < content.length; i++)
      {
        HSSFCell cell = row.createCell(i);
        cell.setCellValue(content[i]);
      }
    }

    HSSFSheet parameterSheet = null;
    int parameterSheetIndex = 1;

    parameterSheet = workbook.getSheetAt(parameterSheetIndex++);
    rowNum = 1;
    for (CompanyItem companyItem : companyItems)
    {
      HSSFRow row = parameterSheet.createRow(rowNum++);
      String[] content = companyItem.toContent();

      for (int i = 0; i < content.length; i++)
      {
        HSSFCell cell = row.createCell(i);
        cell.setCellValue(content[i]);
      }
    }

    parameterSheet = workbook.getSheetAt(parameterSheetIndex++);
    rowNum = 1;
    for (DistrictItem districtItem : districtItems)
    {
      HSSFRow row = parameterSheet.createRow(rowNum++);
      String[] content = districtItem.toContent();

      for (int i = 0; i < content.length; i++)
      {
        HSSFCell cell = row.createCell(i);
        cell.setCellValue(content[i]);
      }
    }

    parameterSheet = workbook.getSheetAt(parameterSheetIndex++);
    rowNum = 1;
    for (RegionItem regionItem : regionItems)
    {
      HSSFRow row = parameterSheet.createRow(rowNum++);
      String[] content = regionItem.toContent();

      for (int i = 0; i < content.length; i++)
      {
        HSSFCell cell = row.createCell(i);
        cell.setCellValue(content[i]);
      }
    }

    parameterSheet = workbook.getSheetAt(parameterSheetIndex++);
    rowNum = 1;
    for (TougueItem tougueItem : tougueItems)
    {
      HSSFRow row = parameterSheet.createRow(rowNum++);
      String[] content = tougueItem.toContent();

      for (int i = 0; i < content.length; i++)
      {
        HSSFCell cell = row.createCell(i);
        cell.setCellValue(content[i]);
      }
    }

    this.export2ExcelFile(workbook.getBytes());
  }

  private void export2ExcelFile(byte[] byteArray)
  {
    BufferedOutputStream os = null;
    try
    {
      File file = new File("c://OTWTeamCoordinator.xls");
      if (!file.exists())
      {
        file.createNewFile();
      }
      os = new BufferedOutputStream(new FileOutputStream(file));
      os.write(byteArray);
    }
    catch (IOException ex)
    {
      Logger.getLogger(ExportHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally
    {
      if (os != null)
      {
        try
        {
          os.close();
        }
        catch (IOException ex)
        {
          Logger.getLogger(ExportHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }

  private String[] genContent(ExportItem item)
  {
    String teamId = "" + item.getTeamId();
    String teamNo = item.getTeamNo() != null ? item.getTeamNo() : "Enabled Team not Found";
    String teamCategory = item.getTeamCategory() != null ? item.getTeamCategory() : "";
    String teamCompanyID = "" + item.getTeamCompanyID();
    String teamCompanyNameEn = "COMPANY_OR_ORGANISATION_TEAM".equals(item.getTeamCategory()) ? this.getCompanyNameEn(item.getTeamCompanyID()) : "";
    String teamComapnyNameCh = "COMPANY_OR_ORGANISATION_TEAM".equals(item.getTeamCategory()) ? this.getCompanyNameCh(item.getTeamCompanyID()) : "";
    String teamCoorCompanyNameEn = this.getCompanyNameEn(item.getCompanyId());
    String teamCoorCompanyNameCh = this.getCompanyNameCh(item.getCompanyId());
    String coodinatorId = String.valueOf(item.getId());
    String teamCoorCompanyId = item.getCompanyId() > 0 ? "" + item.getCompanyId() : "";
    String companyCoorId = item.getCompanyCoordinatorId() > 0 ? "" + item.getCompanyCoordinatorId() : "";
    String chName = item.getChName();
    String chSurname = item.getChSureName();
    String enFirstName = item.getEnFirstName();
    String enMiddleName = item.getEnMiddleName();
    String enOtherName = item.getEnOtherName();
    String enLastName = item.getEnLastName();
    String priPhoneCountryCode = item.getPriPhoneCountryCode();
    String priPhoneNo = item.getPriPhoneNo();
    String secPhoneCountryCode = item.getSecPhoneCountryCode();
    String secPhoneNo = item.getSecPhoneNo();
    String email = item.getEmail();
    String estate = item.getEstate();
    String address = item.getAddress();
    String building = item.getBuilding();
    String street = item.getStreet();
    String room = item.getRoom();
    String districtId = item.getDistrict() > 0 ? "" + item.getDistrict() : "";
    String regionId = item.getRegion() > 0 ? "" + item.getRegion() : "";
    String tongueId = item.getTongueId() > 0 ? "" + item.getTongueId() : "";
    String title = item.getTitle();
    String type = item.getType();
    String status = item.getStatus();
    String correspondenceType = item.getCorrespondenceType();
    String job = item.getJob();
    String defaluted = item.isDefaulted() ? "1" : "0";
    String disabled = item.isDisabled() ? "1" : "0";

    return new String[]
    {
      teamId, teamNo, teamCategory, teamCompanyID, teamComapnyNameCh, teamCompanyNameEn, coodinatorId, teamCoorCompanyId, 
      teamCoorCompanyNameCh, teamCoorCompanyNameEn, chSurname, chName, enFirstName, enMiddleName, enLastName, enOtherName,
      priPhoneCountryCode, priPhoneNo, secPhoneCountryCode, secPhoneNo, email, estate, address, building,
      street, room, districtId, regionId, tongueId, title, type, status, correspondenceType, job, defaluted, disabled, companyCoorId
    };
  }

  public static ExportHandler get()
  {
    return HANDLER;
  }

  private ExportHandler()
  {

  }

  private String getCompanyNameEn(int companyId)
  {   
    CompanyItem item = this.allCompanyMap.get(companyId);
    if (item != null)
    {
      return item.getNameEn() != null ? item.getNameEn() : "";
    }

    return "";
  }

  private String getCompanyNameCh(int companyId)
  {
    CompanyItem item = this.allCompanyMap.get(companyId);
    if (item != null)
    {
      return item.getNameCH() != null ? item.getNameCH() : "";
    }

    return "";
  }
}
